﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using SimpleContainer;
using SimpleContainer.Extensions;

namespace SimpleContainer
{
    public static class SimpleContainerWebRequestLifetime
    {

        public static void RegisterForOneRequest(this SimpleContainer container, string key, Type serviceType, Func<SimpleContainer, Type, string, object> creator)
        {
            if (serviceType == null)
            {
                throw new ArgumentNullException("serviceType");
            }
            if (creator == null)
            {
                throw new ArgumentNullException("creator");
            }
            var keyForRequestItem = serviceType.AssemblyQualifiedName + "...";
            container.Register(serviceType, key, (c, type, k) =>
            {
                var keyToUse = keyForRequestItem + k;
                var instances = SimpleContainerWebRequestLifetimeModule.GetInstances();
                return instances.GetOrAdd(keyToUse, (kk) => creator(c, type, kk));
            });
        }

        public static void RegisterForOneRequest(this SimpleContainer container, Type serviceType, Func<SimpleContainer, Type, string, object> creator)
        {
            container.RegisterForOneRequest(null, serviceType, creator);
        }


        public static void RegisterForOneRequest<T>(this SimpleContainer container, string key, Func<SimpleContainer, Type, string, object> creator)
            where T : class
        {
            container.RegisterForOneRequest(key, typeof(T), creator);
        }

        public static void RegisterForOneRequest<T>(this SimpleContainer container, Func<SimpleContainer, Type, string, object> creator)
            where T : class
        {
            container.RegisterForOneRequest(null, typeof (T), creator);
        }



        public static void RegisterForOneRequest<T, TImplementation>(this SimpleContainer container)
            where T : class
        {
            container.RegisterForOneRequest<T>(null, SimpleContainerExtensions.GetCreator<TImplementation>());
        }

        public static void RegisterForOneRequest<T, TImplementation>(this SimpleContainer container, string key)
            where T : class
        {
            container.RegisterForOneRequest<T>(key, SimpleContainerExtensions.GetCreator<TImplementation>());
        }

    }
}
